clc,clear
% csv 2 offset
path = 'F:\ITEMS\yunhui\M11\POST\DataA';
r = readmatrix(strcat(path,'\R65.csv'));
g = readmatrix(strcat(path,'\G65.csv'));
b = readmatrix(strcat(path,'\B65.csv'));

base_gray = 64;
gamma = 2.2;

center_size = 500/2;

if size(r,2)==size(b,2) && size(r,2)<size(g,2)
    r_exp = imresize(r,size(g));
    b_exp = imresize(b,size(g));
    g_exp = g;
else
    r_exp = r;
    g_exp = g;
    b_exp = b;
end

r_center = mean2(r_exp(end/2-center_size:end/2+center_size,end/2-center_size:end/2+center_size));
g_center = mean2(r_exp(end/2-center_size:end/2+center_size,end/2-center_size:end/2+center_size));
b_center = mean2(r_exp(end/2-center_size:end/2+center_size,end/2-center_size:end/2+center_size));

%% multi-graylevel gamma fit
% set lumi = A*x^gamma

%% STD_LUM = A*(GRAY/255)^GAMMA
Ar = r_center/((base_gray/255)^gamma);
Ag = g_center/((base_gray/255)^gamma);
Ab = b_center/((base_gray/255)^gamma);
offsetr = ((r/Ar).^(1/gamma)).*255;
offsetr = -(offsetr-base_gray);
offsetg = ((g/Ag).^(1/gamma)).*255;
offsetg = -(offsetg-base_gray);
offsetb = ((b/Ab).^(1/gamma)).*255;
offsetb = -(offsetb-base_gray);
writematrix(single(offsetr),strcat(path,'\offsetR.csv'));
writematrix(single(offsetg),strcat(path,'\offsetG.csv'));
writematrix(single(offsetb),strcat(path,'\offsetB.csv'));